﻿using ApplicationModels.A02.Identities;
using ApplicationModels.A07.Chats;
using Commons.Helpers;
using EntityModels.E02.Identities;
using EntityModels.E07.Chats;
using IApplicationServices;
using Microsoft.AspNetCore.SignalR;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;

namespace WebAPI.Hubs
{
    public class ChatHub:Hub
    {
        private readonly IConversationService _conversationService;
        private readonly IMessageService _messageService;
        private readonly RedisHelper redisHelper;
        public ChatHub(IConversationService conversationService, IMessageService messageService)
        {
            _conversationService = conversationService;
            _messageService = messageService;
            redisHelper = new RedisHelper();
        }

        public async Task SendMessage(string conversationId, string senderId, string content)
        {
            
            //发送者Id
            var user = (await _messageService.Repository.GetOtherByIdAsync<Guid, AppUser>(Guid.Parse(senderId))).Data;
            DateTime time = DateTime.Now;
            var conver = (await _conversationService.GetAsync(x => x.Id == int.Parse(conversationId))).Data;
            var receiverId = conver.ParticipantIds.FirstOrDefault(x => x != senderId);
            if (conver == null)
            {
                conver = new ConversationAM(senderId,receiverId,content);
                await _conversationService.AddAsync(conver);    
            }
            MessageAM message = new MessageAM(conver.Id,senderId, content);
            await _messageService.SendMessageAsync(conver, message);
            //获取接收者的连接Id
            var receiverConnectionId = await redisHelper.StringGetAsync($"user:{receiverId}");
            if (receiverConnectionId != null)
            {
                // 发送消息给接收者
                await Clients.Client(receiverConnectionId).SendAsync("ReceiveMessage",user.Id, user.Avatar, content, time);
            }
            //await Clients.Caller.SendAsync("MessageSent", new
            //{
            //    MessageId = message.Id,
            //    Timestamp = time
            //});
        }
        public override async Task OnConnectedAsync()
        {
            // 获取请求的 access_token
            var accessToken = Context.GetHttpContext()?.Request.Query["access_token"].ToString();

            if (!string.IsNullOrEmpty(accessToken))
            {
                // 解析 access_token 获取 userId
                var userId = GetUserIdFromToken(accessToken);

                if (userId != null)
                {
                    // 注册连接信息
                    await RegisterUser(userId);
                    Console.WriteLine($"User {userId} connected.");
                    await base.OnConnectedAsync();
                }
                else
                {
                    
                    Console.WriteLine("Invalid token or userId not found.");
                    await base.OnConnectedAsync();
                    return;
                }
            }
            else
            {
                Console.WriteLine("access_token is missing.");
                await base.OnConnectedAsync();
                return;
            }
        }
        public async Task RegisterUser(string userId)
        {
            // 存储 UserId -> ConnectionId
            await redisHelper.StringSetAsync($"user:{userId}", Context.ConnectionId);
            await Clients.Caller.SendAsync("Registered", "用户绑定成功");
        }
        private string GetUserIdFromToken(string token)
        {
            var handler = new JwtSecurityTokenHandler();
            var jsonToken = handler.ReadToken(token) as JwtSecurityToken;

            if (jsonToken != null)
            {
                // 假设 userId 存储在 token 的 "nameid" 声明中
                var userIdClaim = jsonToken.Claims.FirstOrDefault(c=>c.Type == ClaimTypes.NameIdentifier);

                return userIdClaim?.Value;
            }
            return null; // 如果无法解析，则返回 null
        }
    }
}
